/*
 * @Author: zhengzhuang
 * @Date: 2020-05-16 15:28:15
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-11-10 11:20:29
 * @Description: In User Settings Edit
 * @FilePath: /C20Driver/lib/service/socket_manage.dart
 */
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:C20Driver/config/service_api.dart';
import 'package:C20Driver/model/driver_information_model.dart';
import 'package:C20Driver/provider/driver_information.dart';
import 'package:C20Driver/provider/position_information.dart';
import 'package:C20Driver/utils/locate_info.dart';
import 'package:C20Driver/utils/order_monitoring.dart';
import 'package:C20Driver/utils/permission_handler.dart';
import 'package:provider/provider.dart';
import '../utils/toast.dart';
import 'mqtt_manage.dart';

/* *
 * socket服务
 */
class SocketManage {
  // 私有
  SocketManage._();

  // 静态
  static SocketManage _manager;

  // 提供访问
  factory SocketManage() {
    if (_manager == null) {
      _manager = new SocketManage._();
    }
    return _manager;
  }
  WebSocket _webSocket;

  Future<WebSocket> future;
  bool _connectionStatus = true;

  /// 打开websocket
  void initWebSocket(context, userId) async {
    print('开始链接');

    String path = ServiceApi.socketUrl;
    future = WebSocket.connect(path);
    future.then((webSocket) {
      _webSocket = webSocket;
      webSocket.listen((onData) {
        print('链接成功获取到的数据');
        print(onData);
        _connectionStatus = true;
        var typeTxt = json.decode(onData.toString())['data'];

        if (typeTxt['type'] == '0010') {
          // 初始化socket之后发送个人信息到后台(持续发送司机当前位置)
          fristSendSocket(context, userId);
        }

        if (typeTxt['type'] == '0020' || typeTxt['type'] == '0022') {
          // 正常派单
          OrderMonitoring().getAppOrderMonitoring(context, typeTxt);
        }

        if (typeTxt['type'] == '0033') {
          // 正常派单
          ToastX.top('用户取消订单');
        }
      }, onError: (err) {
        print("服务端==onError" + err);
      }, onDone: () {
        print("服务端==onDone");
        _connectionStatus = false;
        DriverInformation providerUser =
            Provider.of<DriverInformation>(context, listen: false);
        // SocketManage().initWebSocket(context, providerUser.driverInfo.userId);
        MqttManage.getInstance().init(providerUser.driverInfo.userId, context);
      });
    });
  }

  // 初始化socket之后发送个人信息到后台(持续发送司机当前位置)
  void fristSendSocket(context, userId) {
    String str =
        '{"serv": "checkDriverSocketStatus", "data": { "driver_id": $userId}}';
    SocketManage().sendMessage(context, str.toString());

    /// 打开socket
    // UserrealtimeorderProvide provider = Provider.of<UserrealtimeorderProvide>(context, listen: false);
    // String strCx = '{"serv": "driverOnline", "data": { "driver_id": $userId, "current_longitude": ${provider.myLocation['longitude']}, "current_latitude": ${provider.myLocation['latitude']}}}';
    // SocketManage().sendMessage(strCx.toString());

    /// 持续发送司机当前位置
    continuousSendLocation(context, userId);

    // if (orderState == '2') {
    //   UserrealtimeorderProvide provider = Provider.of<UserrealtimeorderProvide>(context);
    //   provider.jumpCurrentOrder(context);
    // }
  }

  // socket发送
  void sendMessage(context, data) {
    if (_connectionStatus) _webSocket.add(data.toString());
    if (!_connectionStatus) {
      DriverInformation providerUser =
          Provider.of<DriverInformation>(context, listen: false);
      // SocketManage().initWebSocket(context, providerUser.driverInfo.userId);
      MqttManage.getInstance().init(providerUser.driverInfo.userId, context);
    }
  }

  /// 司机出车
  Future<bool> driverOnline(BuildContext context) async {
    PositionInformation provider =
        Provider.of<PositionInformation>(context, listen: false);
    DriverInformation driverInformation =
        Provider.of<DriverInformation>(context, listen: false);
    DriverInformationModel info = driverInformation.driverInfo;
    String strCx =
        '{"serv": "driverOnline", "data": { "driver_id": ${info.userId}, "current_longitude": ${provider.driverLocation.longitude}, "current_latitude": ${provider.driverLocation.latitude}}}';
    SocketManage().sendMessage(context, strCx.toString());
    driverInformation.setDriverInformation(workingStatus: '0020');
    return true;
  }

  /// 关闭socket
  /// 停止实时定位
  void stopSocket(context) async {
    _webSocket.close();
  }

  /// 司机收车
  void driverCollection(BuildContext context) {
    LocateInfo().stopLocation(context);
  }

  Timer _timer;

  /// 持续发送司机当前定位
  Future<void> continuousSendLocation(context, userId) async {
    if (_timer != null) {
      _timer.cancel();
    }
    if (await PermissionHandlerX.position(context)) {
      final location = await AmapLocation.fetchLocation();
      Provider.of<PositionInformation>(context, listen: false)
          .setRealtimeDriverPosition(context, location.latLng.latitude,
              location.latLng.longitude, userId);
      _timer = Timer.periodic(Duration(seconds: 8), (timer) async {
        final location = await AmapLocation.fetchLocation();
        Provider.of<PositionInformation>(context, listen: false)
            .setRealtimeDriverPosition(context, location.latLng.latitude,
                location.latLng.longitude, userId);
      });
    }
  }
}
